const Router = require('koa-router')
const { Book, UnDownloadedBook } = require('../db')
const userI = require('../intercepror/user')
const BookSources = require('../BookSources')

const route = new Router({
  prefix: '/netBook'
})

async function checkBookSource (ctx, next) {
  const { BSIndex, BSName } = ctx.request.body
  if (BookSources[BSIndex] && BookSources[BSIndex].name === BSName) {
    await next()
  } else {
    ctx.throw(404, '书源不存在，请不要瞎搞，小心你号没了')
  }
}

route
  .get('/bsList', userI.emailVerified, async ctx => {
    ctx.body = BookSources.map((bookSource, index) => {
      return {
        BSIndex: index,
        BSName: bookSource.name,
        BSSearchOptions: bookSource.searchOptions
      }
    })
  })

  .get('/search', userI.emailVerified, checkBookSource, async ctx => {
    const { BSIndex } = ctx.request.body
    const bookSource = BookSources[BSIndex]
    if (bookSource.searchOptions && bookSource.searchOptions.conditions) {
      const searchKeys = {}
      for (let i = 0; i < bookSource.searchOptions.conditions.length; i++) {
        const key = bookSource.searchOptions.conditions[i].name
        const value = ctx.request.body[key]
        searchKeys[key] = value
      }
      ctx.body = await bookSource.searchBook(searchKeys)
    } else {
      ctx.throw(500, '书源有问题，请联系开发者处理')
    }
  })

  .post('/save', userI.emailVerified, checkBookSource, async ctx => {
    const { book, BSName, BSIndex } = ctx.request.body
    const newBook = new Book({
      name: book.bname,
      author: book.author,
      creator: 'system'
    })
    const savedBook = await newBook.save()

    const unDownloadedBook = new UnDownloadedBook({
      name: savedBook.name,
      author: savedBook.author,
      bookId: savedBook._id,
      type: BSName,
      bookOptions: book
    })
    await unDownloadedBook.save()

    if (BookSources[BSIndex].saveBook && typeof BookSources[BSIndex].saveBook === 'function') {
      await BookSources[BSIndex].saveBook()
    }

    ctx.body = savedBook
  })

module.exports = route
